﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Net.Http;
using System.Net;
using Newtonsoft.Json.Linq;

namespace UserSessionService.WebApi.Tests
{
    [TestClass]
    public class UserSessionTest
    {
        String encodedTestUserId = "dXNlcjFAaG90bWFpbC5jb20";

        // Chage the base address to your local instance.  Port # is likely different.
        private static HttpClient GetHttpClient()
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:3785");
            return client;
        }

        [TestMethod]
        public void Delete()
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage response = client.DeleteAsync("/api/vieweditems/delete").Result;
           Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
        }

        [TestMethod]
        public void AddViewedItem(JObject json)
        {
            var client = GetHttpClient();
            var response = client.PostAsJsonAsync("/api/vieweditems", json).Result;
            Assert.IsTrue(response.IsSuccessStatusCode);
        }

        [TestMethod]
        public void GetViewedItemsWithBadUserId(JObject json)
        {
            var count = 5;

            var client = GetHttpClient();
            var response = client.GetAsync(string.Format("/api/vieweditems/{0}?count={1}", "something not BASE64 encoded", count)).Result;
            Assert.IsTrue(response.StatusCode == HttpStatusCode.Unauthorized);
        }

        [TestMethod]
        public void GetViewedItems()
        {
            var count = 5;

            var client = GetHttpClient();
            var response = client.GetAsync(string.Format("/api/vieweditems/{0}?count={1}", encodedTestUserId, count)).Result;
            Assert.IsTrue(response.IsSuccessStatusCode);

            // Make sure the data is valid.
            JObject json = response.Content.ReadAsAsync<JObject>().Result;
            Assert.IsNotNull(json);
        }

        [TestMethod]
        public void GetViewedItemsForUnknownUserId()
        {
            // Try to get vieweditems for a user that doesn't exist.
            var client = GetHttpClient();
            HttpResponseMessage response = client.GetAsync("/api/vieweditems/someuserthatdoesntexist?count=1").Result;
            Assert.IsTrue(response.StatusCode == HttpStatusCode.NotFound);
        }
    }
}
